package com.example.book.sys.role.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.book.base.BaseController;
import com.example.book.base.Result;
import com.example.book.domain.sys.SysRole;
import com.example.book.domain.sys.SysRoleMenu;
import com.example.book.sys.role.service.SysRoleMenuService;
import com.example.book.sys.role.service.SysRoleService;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author haocj
 * 角色控制器
 */
@RestController
@RequestMapping(value = "/sys/sysRole")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysRoleMenuService roleMenuService;

    @ModelAttribute
    public SysRole get(@RequestParam(required = false) String id) {
        if (StringUtils.isNotBlank(id)) {
            return roleService.get(id);
        } else {
            return new SysRole();
        }
    }

    /**
     * 获取角色列表
     *
     * @param sysRole
     * @return
     */
    @RequestMapping(value = "/info")
    public PageInfo<SysRole> findInfo(SysRole sysRole) {
        return roleService.findPage(sysRole);
    }

    @RequestMapping(value = "/findList")
    public List<SysRole> findiList(SysRole sysRole) {
        return roleService.findList(sysRole);
    }


    /**
     * 修改
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/update")
    public Result update(String id) {

        SysRole sysRole = roleService.get(id);
        SysRoleMenu roleMenu = new SysRoleMenu();
        roleMenu.setRoleId(sysRole.getId());
        List<SysRoleMenu> list = roleMenuService.findList(roleMenu);
        List<String> ids = new ArrayList<String>();

        for (SysRoleMenu sysRoleMenu : list) {
            ids.add(sysRoleMenu.getMenuId());
        }

        JSONObject object = new JSONObject();
        object.put("role", sysRole);
        object.put("list", list);
        object.put("ids", ids);
        return Result.success(object);

    }

    /**
     * 新增、修改角色，以及角色权限
     *
     * @param ids
     * @param sysRole
     * @return
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @RequiresPermissions("sys:role:save")
    public Result save(@RequestParam("mids") String[] ids, SysRole sysRole) {
        roleService.save(sysRole, ids);
        return Result.success("保存成功");
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result delete(@RequestParam("ids") String[] ids) {
        roleService.delete(ids);
        return Result.success();
    }
}
